﻿using Chain.Common.DEncrypt;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class WeiXinPublic_Notify : System.Web.UI.Page
{
    protected string Token = "79b4de7cf79777bf4af9e213ede350af";//你的token
    protected string _returnStr = "";//你的token
    protected void Page_Load(object sender, EventArgs e)
    {
        string postStr = "";
        if (Request.HttpMethod.ToLower() == "post")
        {
            System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;

            byte[] b = new byte[s.Length];

            s.Read(b, 0, (int)s.Length);

            postStr = System.Text.Encoding.UTF8.GetString(b);
            string _resStr = "";

            if (!string.IsNullOrEmpty(postStr))
            {
                _resStr = ResponseMsg(postStr);
                WriteFileLog(postStr);
            }
            Response.Write(_resStr);
            Response.End();
        }
        else
        {
            Valid();
        }
    }
    /// <summary>
    /// 验证微信签名
    /// </summary>
    /// * 如果参数正确则返回随机字符
    /// <returns></returns>
    private void Valid()
    {
        string echoStr = Request.QueryString["echoStr"].ToString();
        if (CheckSignature())
        {
            if (!string.IsNullOrEmpty(echoStr))
            {
                Response.Write(echoStr);
                Response.End();
            }
        }


    }
    /// <summary>
    /// 验证微信签名
    /// </summary>
    /// * 将token、timestamp、nonce三个参数进行字典序排序
    /// * 将三个参数字符串拼接成一个字符串进行sha1加密
    /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。
    /// <returns></returns>
    private bool CheckSignature()
    {

        string signature = Request.QueryString["signature"].ToString();
        string timestamp = Request.QueryString["timestamp"].ToString();
        string nonce = Request.QueryString["nonce"].ToString();
        string[] ArrTmp = { Token, timestamp, nonce };
        Array.Sort(ArrTmp);     //字典排序
        string tmpStr = string.Join("", ArrTmp);
        tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
        tmpStr = tmpStr.ToLower();
        if (tmpStr == signature)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    /// <summary>
    /// 返回信息结果(微信信息返回)
    /// </summary>
    /// <param name="weixinXML"></param>
    private string ResponseMsg(string weixinXML)
    {
        XmlDocument xx = new XmlDocument();
        xx.LoadXml(weixinXML);

        XmlNode root = xx.SelectSingleNode("xml");

        XmlNode _ToName = root.SelectSingleNode("ToUserName");
        XmlNode _FromName = root.SelectSingleNode("FromUserName");
        XmlNode _CreatTime = root.SelectSingleNode("CreateTime");
        XmlNode _MsgType = root.SelectSingleNode("MsgType");

        #region Click/View 事件处理
        if (_MsgType.InnerText == "event")
        {
            XmlNode _Event = root.SelectSingleNode("Event");
            XmlNode _EventKey = root.SelectSingleNode("EventKey");
            if (_Event.InnerText == "subscribe")
            {
                //关注后返回信息代码
                _returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[欢迎关注,请输入账号 密码进行绑定！]]></Content></xml>";

                return _returnStr;

            }

            #region  click事件
            if (_Event.InnerText == "CLICK")
            {

                //请求和客服对话，关键词：rgfw
                if (_EventKey.InnerText == "rgfw")
                {
                    //文字信息
                    _returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>";
                    return _returnStr;
                }
                else
                {
                    //关键词：piclist自动回复图文信息
                    if (_EventKey.InnerText == "piclist")
                    {
                        //DataTable dt = new DataTable();
                        //dt = dal.GetList(8, "CID=525", "ID desc");   //获取需要回复的图文信息列表
                        //StringBuilder sbpic = new StringBuilder();
                        //if (dt != null && dt.Rows.Count > 0)
                        //{
                        //    sbpic.Append("<xml>");
                        //    sbpic.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", _FromName.InnerText);
                        //    sbpic.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", _ToName.InnerText);
                        //    sbpic.AppendFormat("<CreateTime><![CDATA[{0}]]></CreateTime>", ConvertDateTimeInt(DateTime.Now));
                        //    sbpic.AppendFormat("<MsgType><![CDATA[{0}]]></MsgType>", "news");
                        //    sbpic.AppendFormat("<ArticleCount><![CDATA[{0}]]></ArticleCount>", dt.Rows.Count);
                        //    sbpic.Append("<Articles>");
                        //    foreach (DataRow dr in dt.Rows)
                        //    {
                        //        sbpic.Append("<item>");
                        //        sbpic.AppendFormat("<Title><![CDATA[{0}]]></Title>", dr["Title"]);  //标题
                        //        sbpic.AppendFormat("<Description><![CDATA[{0}]]></Description>", dr["Des"]);  //导读
                        //        sbpic.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl>", "http://www.xxx.com/" + dr["Pic"]);  //图片地址url
                        //        sbpic.AppendFormat("<Url><![CDATA[{0}]]></Url>", "http://www.xxx.com/test.aspx?id=" + dr["ID"]);   //原文链接
                        //        sbpic.Append("</item>");
                        //    }

                        //    sbpic.Append("</Articles></xml>");

                        //    _returnStr = sbpic.ToString();
                        //    return _returnStr;
                        //}
                    }

                }
            }
            #endregion

        }
        #endregion

        #region View事件   关键词自动回复文字或图片信息处理
        if (_MsgType.InnerText == "text")
        {
            XmlNode _Content = root.SelectSingleNode("Content");
            string[] pws = _Content.InnerText.Split(' ');
            //关键词：
            if (!string.IsNullOrEmpty(_Content.InnerText) && pws.Length == 2)
            {
                string account = pws[0];
                string pwd = DESEncrypt.Encrypt(pws[1]);
                Chain.BLL.Mem BllMem = new Chain.BLL.Mem();
                DataSet ds = BllMem.GetList(" memcard=" + account);
                if (ds.Tables[0].Rows.Count>0)
                {
                    string zpwd = ds.Tables[0].Rows[0]["mempassword"].ToString();
                    if (zpwd==pwd)
                    {
                        Chain.Model.Mem ModelMem = BllMem.GetModel(account);
                        ModelMem.MemWeiXinCards = _FromName.InnerText;
                        _returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[绑定成功！]]></Content></xml>";
                        return _returnStr;
                    }
                    else
                    {
                        _returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[密码错误！]]></Content></xml>";
                        return _returnStr;
                    }
                }
                else
                {
                    _returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[账号不存在！]]></Content></xml>";
                    return _returnStr;
                }
          
                //_returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>";
                //return _returnStr;
            }
            else
            {
                //文字信息
                _returnStr = "<xml><ToUserName><![CDATA[" + _FromName.InnerText + "]]></ToUserName><FromUserName><![CDATA[" + _ToName.InnerText + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[您的意思我不是很明白!如果需要绑定微信请输入账号 密码]]></Content></xml>";
                return _returnStr;
            }

        }
        #endregion

        return _returnStr;
    }


    /// <summary>
    /// unix时间转换为datetime
    /// </summary>
    /// <param name="timeStamp"></param>
    /// <returns></returns>
    private DateTime UnixTimeToTime(string timeStamp)
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeStamp + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        return dtStart.Add(toNow);
    }

    /// <summary>
    /// datetime转换为unixtime
    /// </summary>
    /// <param name="time"></param>
    /// <returns></returns>
    private int ConvertDateTimeInt(System.DateTime time)
    {
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        return (int)(time - startTime).TotalSeconds;
    }
    /// <summary>
    /// 写入文件日志
    /// </summary>
    /// <param name="strMemo"></param>
    private void WriteFileLog(string strMemo)
    {
        string _filepath = Server.MapPath("/logs");
        string _filename = Server.MapPath("/logs/logs.log");

        if (!Directory.Exists(_filepath))
        {
            Directory.CreateDirectory(_filepath);
            if (!File.Exists(_filename))
            {
                FileStream fs1 = File.Create(_filename);
                fs1.Close();
                fs1.Dispose();
            }
        }

        //将文件信息读入流中
        using (FileStream fs = new FileStream(_filename, FileMode.OpenOrCreate | FileMode.Append))
        {
            lock (fs)//锁住流
            {
                //if (!fs.CanWrite)
                //{
                //    throw new System.Security.SecurityException("文件fileName=" + _filename + "是只读文件不能写入!");
                //}

                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(strMemo);
                sw.Dispose();
                sw.Close();
            }
        }

    }
}